package me.huanmeng.heater.runnable;

import cn.hutool.core.util.RandomUtil;
import lombok.Getter;
import me.huanmeng.heater.Heater;
import me.huanmeng.heater.api.event.PongEvent;
import me.huanmeng.heater.event.EventHandler;
import me.huanmeng.heater.event.Tip;
import me.huanmeng.heater.main.HeaterMain;
import me.huanmeng.heater.socket.BotSocketClient;
import me.huanmeng.heater.socket.HeartBeatPacket;
import org.java_websocket.framing.CloseFrame;

/**
 * 2021/9/26<br>
 * Heater<br>
 * 心跳包现场
 *
 * @author huanmeng_qwq
 */
@Getter
@EventHandler
@Tip("System")
public class HeartBeatRunnable extends Thread {
    private final BotSocketClient botSocketClient;
    private final HeartBeatPacket heartBeatPacket;
    private int pong = 0;

    public HeartBeatRunnable(BotSocketClient botSocketClient) {
        this.botSocketClient = botSocketClient;
        heartBeatPacket = new HeartBeatPacket(botSocketClient);
        Heater.registerEvents(null, this);
        start();
    }

    @Override
    public void run() {
        while (HeaterMain.getInstance().isRunning()) {
            //(间隔为30+(-5,5)
            final int sec = (30 * 1000) + RandomUtil.randomInt(-5000, 5000);
            try {
                Thread.sleep(sec);
                if (pong <= 1) {
                    heartBeatPacket.send();
                    ++pong;
                } else {
                    botSocketClient.close(CloseFrame.NORMAL, "未能收到pong");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void onPong(PongEvent e) {
        pong = 0;
    }
}
